<style lang="less" scoped>
/deep/.el-dialog--center .el-dialog__body {
  padding: 0px 0 0px 0px;
}

.dialog_content {
  padding: 10px 30px;

  .progress-title {
    text-align: right;
    width: 100px;
    padding: 0px;

  }

  .progress-content {
    // width: 300px;
    // background-color: red;
    display: inline;

    ::v-deep .el-progress-bar {
      width: 500px;
    }

  }


}

.f30i {
  font-size: 30px !important;
  // line-height: 36px;
}

.el-button--test {
  //30/91 160
  color: rgb(36, 112, 176);
  background-color: white;
}

.el-button+.el-button {
  margin-left: 20px;
}

.el-button--clearBackground {

  border: 0px solid transparent;
  background-color: transparent;
  color: #0a70b0;
  line-height: 40px;

}

/deep/.transItem .el-form-item__content {
  line-height: 24px !important;
}

.importResultDialog {
  /deep/.el-dialog {
    box-sizing: border-box;

    .el-dialog__footer {
      text-align: center;
    }

    /deep/.el-dialog__body {
      box-sizing: border-box;
      // height: 100%;
    }
  }

  ::v-deep .el-form-item__label {
    padding: 0px;
    text-align: right;

  }
}


/*兼容火狐/deep/失效问题*/
.importResultDialog {
  /deep/.el-dialog {
    box-sizing: border-box;

    .el-dialog__body {
      box-sizing: border-box;
      // height: 100%;
    }
  }
}

.cancelImportDialog {
  ::v-deep .el-dialog__body {
    padding: 0px;

    // height: 100%;
  }
}

.data-statistics {
  font-size: 18px;
  font-weight: bold;
}

.file-select {
  display: inline-block;
  height: 36px;
  width: 665px;
  border: 1px solid rgb(220, 223, 230);
  border-radius: 4px;
  line-height: 36px;
  padding-left: 15px;
  cursor: pointer;
}

.file_button {
  cursor: pointer;

}

.importResultDialog {
  min-height: 500px;
  max-height: 1000px;
}

.el-checkbox {
  margin-right: 15px;
}

.pb7 {
  padding-bottom: 7px;
}

.disableStatus {
  color: #aaaaaa;
  cursor: not-allowed;

}

.disableLabelStatus {
  color: #aaaaaa;
  background-color: #F5F7FA;
  border-color: #E4E7ED;
  // color: gray;

  // background-color: rgba(128, 128, 128,0.3);
  cursor: not-allowed;

}
</style>
<template>
  <div>

    <!-- 展示导入结果弹框 -->

    <el-dialog v-el-drag-dialog class="importResultDialog" title="影像导入" :append-to-body='true'
      :visible.sync="importDialogShow" :before-close="importDialogClose" width="1000px" top="3%" center>
      <div class="clear_fixed bbd" style="height:100%;overflow-y: auto;margin-top: -7px;">

        <div class="dialog_content">
          <el-form class="clear_fixed w100" :model="dialogData" :rules="dialogDataRules" ref="dialogDataForm">
            <div class="clear_fixed pb7">
              <div class="w100 mt30 clear_fixed">
                <el-form-item label="系统名称：" label-width="100px" class="fl " prop="system_id">
                  <el-select :disabled="group !== 'tenancy' || dialogStatus !== 0" v-model="dialogData.system_id"
                    placeholder="请选择系统名称" size="medium" style="width:265px" @change="systemIdChange" clearable>
                    <el-option v-for="item in systemsLiteList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="机构名称：" label-width="100px" class="fl ml50" prop="institution_id">
                  <el-select
                    :disabled="institutionsLiteList.length === 0 || (group !== 'tenancy' && !ksyxlbPermission && jgyxlbPermission) || dialogStatus !== 0"
                    v-model="dialogData.institution_id" placeholder="请选择机构名称" size="medium" style="width:265px" clearable>
                    <el-option v-for="item in institutionsLiteList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <br />
                <el-form-item class="mt20 fl" label="文件夹：" label-width="100px" prop="files_path">
                  <label for="submitInput" class="file-select" :disabled="dialogStatus !== 0"
                    :class="dialogStatus !== 0 ? 'disableLabelStatus' : ''"><span>{{ dialogData.files_path
                    }}</span></label>
                  <input id="submitInput" type="file" @change="fileChange" ref="fileRef"
                    style="width: 700px; display: none;" webkitdirectory :disabled="dialogStatus !== 0">
                </el-form-item>

                <el-form-item class="fl ml10 mt20 ">
                  <el-button title="文件夹" @click="shouldSelectedFiles" type="clearBackground"
                    :disabled="dialogStatus !== 0" class="w36 h36 nop ml10 file_button"><i
                      class="iconfont f30i file_button" :class="dialogStatus !== 0 ? 'disableStatus' : ''"
                      :disabled="dialogStatus !== 0">&#xe7f9;</i></el-button>
                </el-form-item>

              </div>
            </div>
          </el-form>

          <!-- 进度条 -->
          <!--  -->
          <div class="h50" v-if="progressShow">
            <div class="fl progress-title">导入进度：</div>
            <div class="progress-content"> <el-progress :percentage="percentage"></el-progress></div>
            <div>文件数量（{{ didUploadFilesCount }}/{{ allCurrentFilesCount }}）</div>
          </div>

          <div v-show="successListData.length > 0 || failFileList.length
            > 0" class="data-statistics">本次导入{{ allFilesCount }}个文件，
            <span class="clr_green">成功{{ allSuccessCount }}个，</span>
            <span class="clr_red"> 失败{{ currentFailureCount }}个</span>
            <span v-show="cancelFilesCount > 0" class="clr_red"> ，取消{{ cancelFilesCount }}个</span>
          </div>

          <div style="width: 940px; height: 260px;" v-if="successListData.length > 0">
            <div class="h40 mb10 mt10"
              style="background-color: rgba(28, 181, 74, 0.1); border-radius: 5px;  text-align: center; line-height: 40px;">
              <div class="clr_green h40 f14"><i class="iconfont mr5">&#xe6aba;</i>导入成功</div>
            </div>
            <el-table :data="successListData" border max-height="200px" @header-dragend="tableHeaderDragend"
              :header-cell-style="{ background: '#F5F5F5', color: '#333' }" highlight-current-row
              header-row-class-name="strong" ref="importTab">
              <!-- <el-table-column fixed="left"></el-table-column> -->
              <el-table-column align="center" fixed="left" width="100" prop="patient_name" label="患者姓名"></el-table-column>
              <common-table :propData="propData"></common-table>
            </el-table>
          </div>
          <div style="width: 940px; height: 260px; " class="mt5" v-if="failListData.length > 0">
            <div class="h40 mb10"
              style="background-color: rgba(255, 111, 111, 0.1); border-radius: 5px;  text-align: center; line-height: 40px;">
              <div class="clr_red h40 f14"><i class="iconfont mr5">&#xe6ed;</i>导入失败</div>
            </div>
            <el-table :data="failureTabData" max-height="200px" border
              :header-cell-style="{ background: '#F5F5F5', color: '#333' }" highlight-current-row
              header-row-class-name="strong">
              <common-table :propData="propData"></common-table>
            </el-table>
            <div class="clr_red pb10 mt20">
              失败原因：
              <div class="mb10 pl10 pr10 pb10 pt10" style="background-color: rgba(245, 245, 245, 1); border-radius: 5px;">
                <div class="f14">导入的数据无法解析，请确认文件内的格式是否正确。</div>
              </div>
            </div>
          </div>
          <div style="width: 940px;  height:260px" class="mt5" v-if="uploadFailData.length > 0">
            <div class="h40 mb10 mt10"
              style="background-color: rgba(255, 111, 111, 0.1); border-radius: 5px;  text-align: center; line-height: 40px;">
              <div class="clr_red h40 f14"><i class="iconfont mr5">&#xe6ed;</i>上传失败</div>
            </div>
            <el-table :data="uploadFailData" border max-height="200px"
              :header-cell-style="{ background: '#F5F5F5', color: '#333' }" highlight-current-row
              header-row-class-name="strong">
              <el-table-column align="center" prop="file_name" label="文件名"></el-table-column>
              <el-table-column align="center" prop="reason" label="错误原因"></el-table-column>
              <!-- <el-table-column align="center"   prop="file_path" label="文件路径"></el-table-column> -->

              <!-- <common-table :propData="propData" fixed="left"></common-table> -->
            </el-table>
          </div>

        </div>
        <!-- <div class="bbd mt10" style="height: 2px;"></div> -->

      </div>
      <div slot="footer" class="dialog-footer mt10 clear_fixed">
        <el-button class="fr" type="primary" v-show="!uploadSucessAll" @click="importConfirmClose" size="medium"
          :disabled="dialogStatus === 1 || dialogStatus === 3 || !this.uploadFilevalid">{{
            getConfirmTitle }}</el-button>
        <el-button class="fr mr20" type="test" @click="importDialogClose" size="medium">{{ getCancelTitle }}</el-button>
      </div>
    </el-dialog>

    <!-- 取消导入影像 -->
    <el-dialog class="cancelImportDialog" v-if="cancelImportShow" title="提示" :visible.sync="cancelImportShow"
      width="380px" top="31vh" :before-close="() => { cancelImportShow = false }">
      <div class="pt20 pl20 pb20 bbd h20">
        <!-- <div class="clr_warn mb10">
          <i class="iconfont clr_warn" style="font-size: 20px;">&#xe680;</i>
          <span class="f16 ml5">
            重新导入
          </span>
        </div> -->
        <div class="pb10 f16"><i class="iconfont clr_warn mr5"
            style="font-size: 18px;">&#xe680;</i><span>确定取消本次影像导入？</span></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelImportShow = false">取消</el-button>
        <el-button size="small" type="primary" @click="cancelImportSure">确定</el-button>
      </span>
    </el-dialog>
    <!-- 导入失败影像  -->
    <el-dialog v-if="reImportImage" title="提示" :visible.sync="reImportImage" width="380px" top="31vh"
      :before-close="handleClose">
      <div class="pt20 pl20 pb20 bbd">
        <div class="clr_warn mb10">
          <i class="iconfont clr_warn" style="font-size: 20px;">&#xe680;</i>
          <span class="f16 ml5">
            重新导入
          </span>
        </div>
        <div class="pb10">本次将重新导入失败的影像</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取消</el-button>
        <el-button size="small" type="primary" @click="handleSure">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import CommonTable from '@/components/common/CommonTable'
import { mapGetters } from 'vuex'
import moment from 'moment'
import { UploadImageFile, imgUpload, getUuid } from '@/utils/pacs/uploadImage';
import { promiseState } from '@/utils/commons/common.js'
import axios from 'axios'
export default {
  // directive:{
  //     elDragDialog,
  //   },
  data() {

    let requiredValidator = function (tip) {
      return (rule, value, callback) => {

        if (value === '' || value === undefined) {
          callback(new Error(tip))
        } else {
          callback()
        }
      }
    }

    return {

      files: [],//需要去重
      isCanceled: false,
      uploadFilevalid: false,
      cancelImportShow: false,
      isReImport: false,
      progressShow: false,
      cancelDidShow: false,
      percentage: 0,
      allFilesCount: 0,
      allSuccessCount: 0,

      currentCancelFilesCount: 0,
      cancelFilesCount: 0,
      currentFailureCount: 0,
      allCurrentFilesCount: 0,
      didUploadFilesCount: 0,
      reImportImage: false,
      conforimTitle: '导入',
      cancelTitle: '取消',

      currentUploadGuid: '',
      successTabData: [],
      failureTabData: [],
      successListData: [],
      lastSuccessListData: [],
      failListData: [],
      uploadFailData: [],
      failFileList: [],
      dialogTitle: '',
      institutionsLiteList: [],
      jgyxlbPermission: false,
      ksyxlbPermission: false,
      dialogStatus: 0,//弹框状态  0 初始状态 1 上传中 2上传结束（包含取消成功的）
      uploadSucessAll: false,
      source: axios.CancelToken.source(),
      dialogData: {
        id: 0,
        system_id: '',
        institution_id: '',
        files_path: '',
      },
      dialogDataRules: {
        system_id: [{
          required: true,
          trigger: 'blur',
          validator: requiredValidator('请选择系统名称')
        }],
        institution_id: [{
          required: true,
          trigger: 'blur',
          validator: requiredValidator('请选择机构名称')
        }],
        files_path: [{
          required: true,
          trigger: 'blur',
          validator: requiredValidator('请选择需要上传的文件')
        }],
      },
      propData: [
        // {
        //   prop:'patient_name',
        //   label:'患者姓名',
        //   width:130,
        // },
        {
          prop: 'patient_id',
          label: '患者编号',
          width: 130
        },
        {
          prop: 'patient_sex',
          label: '性别',
          width: 60,
          formatter: function (row) {
            const sexMapping = {
              M: '男',
              F: '女',
              O: '未知'
            }
            return sexMapping[row.patient_sex]
          }
        },
        {
          prop: 'patient_age',
          label: '年龄',
          width: 60,
          formatter: function (row) {
            const patient_ageTypeMapping = {
              'Y': '岁',
              'M': '月',
              'D': '日',
              'W': '周'
            }
            let patient_ageNum = ''
            let patient_ageType = ''
            if (row.patient_age) {
              patient_ageNum = row.patient_age.substring(0, row.patient_age.length - 1)
              patient_ageType = row.patient_age.substring(row.patient_age.length - 1, row.patient_age.length)
              return patient_ageNum + patient_ageTypeMapping[patient_ageType]
            } else {
              return ''
            }
          }
        },
        {
          prop: 'patient_birth_date',
          label: '出生日期',
          width: 120,
          formatter: function (row) {
            if (row.patient_birth_date) {
              return moment(row.patient_birth_date).format('YYYY-MM-DD')
            } else {
              return ''
            }
          }
        },
        {
          prop: 'modalities_in_study',
          label: '检查类型',
          width: 80
        },
        {
          prop: 'accession_number',
          label: '检查编号',
          width: 100
        },
        {
          prop: 'study_date_time',
          label: '检查时间',
          width: 158,
          formatter: function (row) {
            if (row.study_date_time) {
              return moment(row.study_date_time).format('YYYY-MM-DD HH:mm:ss')
            } else {
              return ''
            }
          }
        },
        {
          prop: 'series_count',
          label: '序列数',
          width: 66
        },
        {
          prop: 'instance_count',
          label: '实例数',
          width: 65
        },
      ],
    }
  },
  props: [
    'rowId',
    'dialogType',
    'importDialogShow',
    'systemsLiteList',
    'systemId',
    'institutionId',

  ],
  computed: {
    ...mapGetters(['group', 'systemid', "deptInstitutionId"]),

    getConfirmTitle() {
      switch (this.dialogStatus) {
        case 0:
          return '导入'
          break;
        case 1:
          return '导入'
          break;
        case 2:
          return (this.failFileList.length > 0) ? '重新导入' : '确定'
          break;
        case 3:
          return '重新导入'
          break;
        default:

          return (this.failFileList.length > 0) ? '重新导入' : '确定'

          break;
      }
      // return (this.failListData.length > 0 || this.uploadFailData.length > 0) ? '重新导入' : '确定'


    },
    getCancelTitle() {
      return (this.allSuccessCount === this.allFilesCount && this.allSuccessCount !== 0) ? '关闭' : '取消'

    },
  },

  watch: {

    // 'dialogData.system_id': {
    //   handler: function (newVal) {
    //     console.log(newVal)
    //     console.log(this.dialogData.institution_id)
    //     if (newVal === '') {
    //       this.dialogData.system_name = ''
    //       this.dialogData.institutionsLiteList = []
    //     } else {
    //       this.systemsLiteList.forEach((ele) => {
    //         if (ele.id === newVal) {
    //           this.dialogData.system_name = ele.name
    //         }
    //       })
    //       this.dialogData.institution_id = ''
    //       this.dialogData.institutionsLiteList = []

    //       this.getInstitutionsLiteList(newVal) // 获取机构名称
    //       //   this.getSystemDetail(newVal)
    //     }
    //   },

    //   immediate: true
    // },
  },
  async mounted() {



    const permissionArr = JSON.parse(sessionStorage.getItem('permissionArr')) || []
    this.jgyxlbPermission = permissionArr.some(o => o.code === 'ris_jgyxlb') // 机构
    this.ksyxlbPermission = permissionArr.some(o => o.code === 'ris_ksyxlb') // 系统
    console.log('this打印出来吧', this);

    //根据角色设置默认系统-默认机构
    if (this.group === "dept") {
      // 科室角色
      this.dialogData.system_id = this.systemid;
      await this.getInstitutionsLiteList(this.dialogData.system_id);
      this.$nextTick(async () => {
        const setObj = JSON.parse(localStorage.getItem('setObj')) || JSON.parse(localStorage.getItem('setPacsObj')) || {}
        if (!this.ksyxlbPermission && this.jgyxlbPermission && setObj?.GeneralCliParameter_WorkInstitutionId) {
          this.dialogData.institution_id = setObj.GeneralCliParameter_WorkInstitutionId

        } else {
          //默认选中机构id
          if ((this.ksyxlbPermission || this.jgyxlbPermission) && (this.deptInstitutionId || setObj?.GeneralCliParameter_WorkInstitutionId)) {
            if (setObj?.GeneralCliParameter_WorkInstitutionId) {
              this.dialogData.institution_id = setObj.GeneralCliParameter_WorkInstitutionId
            }
            if (this.deptInstitutionId) {
              this.dialogData.institution_id = this.deptInstitutionId
            }

          }

        }

      })
    } else if (this.group === "doct") {
      //医生角色，不能选机构和系统
      this.dialogData.system_id = this.systemid;
      await this.getInstitutionsLiteList(this.dialogData.system_id);
      this.$nextTick(async () => {
        this.dialogData.institution_id = this.deptInstitutionId;

      });
    } else {

      // debugger
      if (this.systemId !== undefined) {
        this.dialogData.system_id = this.systemId
        await this.getInstitutionsLiteList(this.dialogData.system_id);
        this.$nextTick(async () => {
          if (this.institutionId !== undefined) {
            this.dialogData.institution_id = this.institutionId
          }
        })

      }

    }


  },
  methods: {
    systemIdChange(val) {
      this.institutionsLiteList = [];
      this.dialogData.institution_id = "";
      if (val) {
        this.getInstitutionsLiteList(val);
      }
    },


    async getInstitutionsLiteList(val) {
      if (val) {
        let res = await this.$pacsApi.pacsApi.getInstitutionsLiteList({ system_id: val })
        let { code, data } = res
        if (code === 0) {
          this.institutionsLiteList = data
        }
      }
    },
    shouldSelectedFiles() {
      console.log('按钮点击了', this.dialogStatus);

      this.$refs.fileRef.value = null
      this.uploadFilevalid = false
      this.$refs.fileRef.dispatchEvent(new MouseEvent('click'))//弹出选择本地文件

    },
    fileChange(event) {

      if (event.target.files.length > 0) {
        let file_path = event.target.files[0].webkitRelativePath
        // console.log('拿到的文件',file_path.split('/')[0]);
        this.dialogData.files_path = file_path.split('/')[0]
        // file_path.replace('/' + event.target.files[0].name, '')
      }

      //判断是否包含子文件夹
      let fileSome = Array.prototype.some
      let fileFind = Array.prototype.findIndex
      let fileMap = Array.prototype.map

      // debugger
      // const hasSub = fileSome.call(this.$refs.fileRef.files, e => e.webkitRelativePath.replace('/', '').indexOf('/') !== -1)
      // if (hasSub) {
      //不允许有子文件夹====去掉限制、现需要大批量导入---需要包含子文件夹
      // this.$message.error('所选文件夹中包含子文件夹，请重新选择')
      // return
      // }
      //
      // this.$refs.fileRef.files.forEach(file=>{
      // let index =  fileFind.call(this.files,fileItem=>
      //     fileItem.name == file.name && fileItem.size == file.size && fileItem.type == file.type

      //   )
      //   if(index == -1){
      //     this.files.push(file)
      //   }
      //   console.log('文件',file);

      // })
      // console.log('长度对吗？',this.files.length);


      const hasIllegalityFile = fileSome.call(this.$refs.fileRef.files, file => {
        let lastIndex = file.name.lastIndexOf('.');
        let type = file.name.substr(lastIndex + 1).toLowerCase();
        if (type !== 'dcm' && type != '' && type != file.name.toLowerCase()) {
          console.log('格式为===type ===', type, file.name);
          this.$message.error(`所选文件夹中包含非dicom文件，请重新选择或删掉【${file.webkitRelativePath}】文件`)
          return true;
        } else {
          return false
        }
      });
      if (hasIllegalityFile) {
        // this.$message.error('所选文件中包含非dicom文件，请重新选择')
        return
      }
      // this.files = this.$refs.fileRef.files


      this.files = fileMap.call(this.$refs.fileRef.files, (i, file) => file.name == file.name + `_i_${i}`)


      this.uploadFilevalid = true
    },


    uploadingImage(files) {

      this.uploadSucessAll = false
      this.progressShow = true
      this.cancelDidShow = false
      this.allCurrentFilesCount = files.length
      this.didUploadFilesCount = 0
      this.percentage = 0
      this.currentCancelFilesCount = 0
      this.uploadFailData = []
      if (!this.isReImport) {
        this.successListData = []
      }
      this.failListData = []
      this.failFileList = []


      if (this.allCurrentFilesCount == 1) {
        let fd = new FormData()
        fd.append('file', files[0])
        imgUpload(
          {
            data: fd,
            front_id: this.currentUploadGuid,
            system_id: this.dialogData.system_id,
            institution_id: this.dialogData.institution_id,
            cancelToken: this.source,
            onUploadProgress: (progressEvent) => {
              this.percentage = Math.round(progressEvent.loaded / progressEvent.total * 100)
              //进度100%的时候开始获取上传结果
            }
          }).then(res => {
            if (res.code === 0) {
              this.uploadSucessAll = true
              //错误怎么显示？
              this.getFileUploadResult();
              this.currentFailureCount = 0
            } else {
              this.currentFailureCount = 1
              this.failFileList = files
              this.uploadFailData.push({ file_name: files[0].name, reason: res.msg, file_path: files[0].webkitRelativePath })
              // this.importResultShow = true
            }
            this.dialogStatus = 2

          }).catch(err => {
            this.failFileList = files
            if (axios.isCancel(err)) {
              this.$message({
                message: '导入已取消',
                type: 'success'
              });
              this.dialogStatus = 0
              this.cancelFilesCount = 1
            } else {
              this.$message.error(err)
              this.dialogStatus = 2
              this.uploadFailData.push({
                file_name: files[0].name, reason: (err instanceof
                  String) ? err : err.message, file_path: files[0].webkitRelativePath
              })
            }
            this.currentFailureCount = 1

          }).finally(() => {
            this.progressShow = false
            this.didUploadFilesCount = 1
            this.allSuccessCount = this.allFilesCount - this.failFileList.length

          })

        // setTimeout(() => {
        //   // debugger
        //   this.cancelImportSure()

        // }, 100);

      } else {

        this.uploadTool = new UploadImageFile(
          {
            system_id: this.dialogData.system_id,
            institution_id: this.dialogData.institution_id,
            front_id: this.currentUploadGuid,
            files: files
          }
        )
        this.uploadTool.callback = {
          sameCallback: (file) => {
            //不大可能有文件重复吧，一个文件夹放不了的。。。。
            //限制支持多文件夹传入、有相同文件的
          },
          cancelback: (count) => {
            this.currentCancelFilesCount = count
          },
          complete: (obj) => {
            // console.log('完成的数据',obj);


            //obj 里边包含有成功的也有失败的，一起返回的
            this.didUploadFilesCount = Object.keys(obj).length;
            let cancelList = Object.keys(obj).filter(key => obj[key].error === '取消上传')

            this.percentage = parseInt(this.didUploadFilesCount / this.allCurrentFilesCount * 100)

            if (this.isCanceled) {


              console.log('取消失败？', this.didUploadFilesCount, this.currentCancelFilesCount, files.length);
              if ((this.didUploadFilesCount + this.currentCancelFilesCount === files.length)) {
                this.loading.close()
                this.loading = null
                this.isCanceled = false
                if (!this.cancelDidShow) {
                  this.cancelDidShow = true

                  if (this.currentCancelFilesCount === 0) {
                    this.$message({
                      message: '取消失败',
                      type: 'error'
                    });
                  } else {
                    this.$message({
                      message: '导入已取消',
                      type: 'success'
                    });
                  }

                }
                this.percentage = 100
              }

            }
            if (this.percentage == 100) {

              this.progressShow = false

              //进度100%的时候开始获取上传结果
              this.dialogStatus = 2
              let failList = Object.keys(obj).filter(key => obj[key].error !== null || obj[key].result.code !== 0)
              let successList = Object.keys(obj).filter(key => obj[key] && obj[key].result && obj[key].result.code === 0)
              this.failFileList = []
              this.failFileList = Array.prototype.filter.call(files, (fileItem,index) => !successList.includes(fileItem.name+ `_index_${index}`))
              this.cancelFilesCount = cancelList.length + this.allCurrentFilesCount - this.didUploadFilesCount
              this.allSuccessCount = this.allFilesCount - this.failFileList.length
              this.currentFailureCount = failList.length - cancelList.length
              this.parseUploadData(files, obj)

            }
            // if (cancelList.length > 0) {
            // let successList = Object.keys(obj).filter(key => obj[key] && obj[key].result && obj[key].result.code === 0)
            //   if (cancelList.length === this.didUploadFilesCount
            //     || (cancelList.length + failList.length) === this.didUploadFilesCount) {
            //     //上传已经取消
            //     this.progressShow = false
            //     this.uploadTool = null
            //     this.dialogStatus = 0

            //     if (!this.cancelDidShow) {
            //       this.cancelDidShow = true
            //       this.$message({
            //         message: '导入已取消',
            //         type: 'success'
            //       });
            //     }




            //   } else {
            //     //上传已经取消但是已经有部分上传成功了
            //     if (!this.cancelDidShow) {
            //       this.cancelDidShow = true
            //       this.$message({
            //         message: '导入已取消，但有部分影像已导入',
            //         type: 'success'
            //       });
            //       this.percentage = 100
            //       this.parseUploadData(files, obj)
            //       this.dialogStatus = 2

            //     }

            //   }
            //   this.failFileList = []
            //   this.failFileList = Array.prototype.filter.call(files, fileItem => !successList.includes(fileItem.name))
            //   this.cancelFilesCount
            //      = cancelList.length + this.allCurrentFilesCount - this.didUploadFilesCount
            //      this.allSuccessCount = this.allFilesCount - this.failFileList.length 

            //      this.currentFailureCount =  failList.length - cancelList.length
            // } else {
            //   this.percentage = parseInt(this.didUploadFilesCount / this.allCurrentFilesCount * 100)
            //   if (this.percentage == 100) {
            //     //进度100%的时候开始获取上传结果
            //     this.parseUploadData(files, obj)
            //     this.dialogStatus = 2
            //     let failList = Object.keys(obj).filter(key => obj[key].error !== null || obj[key].result.code !== 0)
            //     this.failFileList = []
            //     this.failFileList = Array.prototype.filter.call(files, fileItem => failList.includes(fileItem.name))

            //     this.cancelFilesCount
            //      = cancelList.length + this.allCurrentFilesCount - this.didUploadFilesCount
            //      this.allSuccessCount = this.allFilesCount - this.failFileList.length 
            //      this.currentFailureCount =  failList.length - cancelList.length
            //   }

            // }


          },
        }
        this.uploadTool.setUploadQueue();
      }
      this.progressShow = true

    },
    //去掉后缀
    delete() {
      //`_index_${i}`
    },
    parseUploadData(files, obj) {
      this.uploadSucessAll = this.failFileList.length > 0 ? false : true

      this.uploadTool = null
      this.progressShow = false
      let failList = Object.keys(obj).filter(key => obj[key].error !== null || obj[key].result.code !== 0)
      console.log('失败的列表', failList);
      if (failList.length > 0) {
        this.uploadFailData = []
        failList.map(item => {
          let index = Array.prototype.findIndex.call(files, (fileItem, i) => fileItem.name + `_index_${i}` === item)
          if (index != -1) {
            let ele = files[index]
            let keyName = ele.name + `_index_${index}`
            let reason = obj[keyName].result ? obj[keyName].result.msg : obj[keyName].error
            this.uploadFailData.push({ file_name: ele.name, reason, file_path: ele.webkitRelativePath })
          }

        })
      }
      if (failList.length < this.didUploadFilesCount) {

        this.getFileUploadResult();

      } else {
        // this.importResultShow = true
      }
    },
    async getFileUploadResult() {

      let [res, err] = await this.$pacsApi.pacsApi.getUploadImageDetail({ front_id: this.currentUploadGuid })
      if (err) {
        this.$message.error(err)
      }


      let { data, code } = res
      if (code === 0) {
        if (this.isReImport) {
          this.isReImport = false
        }

        //   let resultList = data

        //   this.successListData.forEach(element => {
        //    let filterResult =  data.filter(e=>e.accession_number === element.accession_number&&e.study_instance_uid === element.study_instance_uid)
        //    if(filterResult.length>0){

        //     element.series_instance_uids = [...new Set(element.series_instance_uids.concat(filterResult.reduce((a,b)=>{return a.concat(b.series_instance_uids)},[])))]
        //    element.series_count =   element.series_instance_uids.length
        //    element.instance_count = element.instance_count + filterResult.reduce((a,b)=>{return a + b.instance_count},0)
        //    resultList = resultList.filter(e => !filterResult.includes(e))

        //    }

        //    // data.forEach(e => {
        //     //   if (element.patient_id === e.patient_id
        //     //     && element.accession_number === e.accession_number
        //     //     && element.study_instance_uid === e.study_instance_uid) {
        //     //     element.series_instance_uids = [...new Set(element.series_instance_uids.concat(e.series_instance_uids))]
        //     //     element.series_count = element.series_instance_uids.length
        //     //     element.instance_count = element.instance_count + e.instance_count
        //     //     resultList = resultList.filter(item => item !== e)
        //     //   }

        //     // })

        //   });


        //   this.successListData = [...new Set(resultList)].concat(this.successListData)
        // } else {
        //   this.successListData = data
        // }

        this.successListData = data

      } else {
        this.$message.error(res.message)
      }




    },

    handleClose() {
      this.reImportImage = false

    },
    handleSure() {
      //重新导入
      this.isReImport = true
      this.reImportImage = false
      this.dialogStatus = 3

      this.uploadingImage(this.failFileList)

    },
    importDialogClose() {

      if (this.dialogStatus === 1 || this.dialogStatus === 3) {
        // //取消上传操作

        this.cancelImportShow = true
      } else {
        this.$emit('importDialogClose')
      }
    },

    cancelImportSure() {
      this.cancelImportShow = false
      this.cancelDidShow = false
      this.isCanceled = true
      if (!this.loading) {
        this.loading = this.$loading({
          lock: true,
          text: '取消中...',
          spinner: 'el-icon-loading',
        });
      }

      if (this.uploadTool) {
        this.uploadTool.cancel()

      } else {
        //判断promise状态
        // promiseState(this.source.token.promise).then(state => {
        //   if (state === 'pending') {
        //     this.source.cancel('取消请求')
        //     this.source = axios.CancelToken.source()
        //   }
        // })
      }
      // }
    },

    importConfirmClose() {

      if (this.dialogStatus === 0) {
        //上传操作
        //验证下表单
        this.$refs.dialogDataForm.validate((valid) => {

          if (valid) {
            this.dialogStatus = 1

            this.allFilesCount = this.$refs.fileRef.files.length
            this.currentUploadGuid = getUuid()
            this.uploadingImage(this.$refs.fileRef.files)

          } else {
            return
          }
        })
      } else {
        //重新导入操作
        if (this.failFileList.length > 0) {
          this.reImportImage = true
        }
      }

    },

    tableHeaderDragend() {
      this.$refs.importTab.doLayout()

    },



  },
  components: {
    CommonTable
  }
}
</script>
